package cn.xo68.ide.plugin.action;

import cn.xo68.ide.plugin.common.PluginPathUtils;
import cn.xo68.ide.plugin.common.component.StarupApplicationComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.vfs.VirtualFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CreateGenerateConfigAction extends AnAction {
    private static Logger logger = LoggerFactory.getLogger(CreateGenerateConfigAction.class);

    @Override
    public void actionPerformed(AnActionEvent e) {
        StarupApplicationComponent.getInstance().setLastOperateProject(e.getProject());
        //PluginPathUtils.getCodeGenerateConfigPath();
        VirtualFile selectedFile = e.getData(LangDataKeys.VIRTUAL_FILE);

        String target=PluginPathUtils.getCodeGenereateConfigPath(selectedFile);
        try {
            if(!Files.exists(Paths.get(target))){
                Files.copy(Paths.get(PluginPathUtils.getCodeGenerateConfigPath()),Paths.get(target));
                selectedFile.refresh(false,false);
                logger.info("创建代码生成配置成功");
            }else {
                logger.info("代码生成配置已经存在");
            }

        } catch (IOException e1) {
            logger.error("创建代码生成配置异常",e1);
        }
    }

    @Override
    public void update(AnActionEvent e) {
        VirtualFile selectedFile = e.getData(LangDataKeys.VIRTUAL_FILE);

        String target=PluginPathUtils.getCodeGenereateConfigPath(selectedFile);

        boolean flag=true;
        if(Files.exists(Paths.get(target))){
            flag =false;
        }

        e.getPresentation().setEnabledAndVisible(flag);
    }
}
